package com.mycase.im.boot.websocket.pattern.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mycase.im.boot.entity.communication.ClientMessage;
import com.mycase.im.boot.entity.communication.ResponseMessage;
import com.mycase.im.boot.entity.database.ImCircle;
import com.mycase.im.boot.entity.database.ImUserFriend;
import com.mycase.im.boot.service.CircleService;
import com.mycase.im.boot.service.UserFriendService;
import com.mycase.im.boot.websocket.WebSocketSignal;
import com.mycase.im.boot.websocket.pattern.MessageStrategy;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.websocket.Session;
import java.util.List;
import java.util.Map;

/**
 * 用来处理发布动态的策略器
 * @Author ZhuHJay
 * @Date 2021/9/18 21:28
 */
@Slf4j
@Service
public class PublishDynamic implements MessageStrategy {

    @Autowired
    private CircleService circleService;
    @Autowired
    private UserFriendService userFriendService;

    @Override
    public Boolean isUse(int type) {
        return WebSocketSignal.MESSAGE_CIRCLE_PUBLISH == type;
    }

    @Override
    public void executeHandler(ClientMessage clientMessage,
                               ObjectMapper objectMapper,
                               Map<String, Session> clientMaps,
                               Session mySession) throws Exception {
        log.warn("onMessage -匹配到-> PublishDynamic(发布动态)");

        // 获取数据
        ImCircle imCircle = circleService.findDynamicById(clientMessage.getId());
        // 将数据发送给自己
        ResponseMessage responseMessage =
                    ResponseMessage.success()
                            .appendData("type", WebSocketSignal.MESSAGE_CIRCLE_PUBLISH)
                            .appendData("dynamic", imCircle);
        sendMessage(objectMapper, mySession, responseMessage);
        // 查询该发送动态用户的所有好友, 然后通知在线的好友进行数据的更新
        List<ImUserFriend> friendList = userFriendService.getFriendList(imCircle.getUserId());
        for (ImUserFriend friend : friendList) {
            // 判断好友是否在线
            if( clientMaps.containsKey(friend.getFriendId()) ){
                sendMessage(objectMapper, clientMaps.get(friend.getFriendId()), responseMessage);
            }
        }
    }
}
